連結:https://leetcode.com/problems/last-stone-weight/description/
class Solution {
public int lastStoneWeight(int[] stones) {
//max heap
PriorityQueue<Integer> heap = new PriorityQueue<>((a,b) -> b - a);
for (int i = 0 ; i < stones.length;i++) heap.offer(stones[i]);
while (heap.size() > 1)
{
int a = heap.poll();
int b = heap.poll();
heap.offer(a-b);
}
if (heap.isEmpty()) return 0;
else return heap.poll();
}
}
連結:https://leetcode.com/problems/k-closest-points-to-origin/description/
class Solution {
public int[][] kClosest(int[][] points, int k) {
PriorityQueue<int[]> pq = new PriorityQueue<>((a,b)->a[1]-b[1]);
for(int i = 0; i < points.length; i++){
int sum = points[i][0] * points[i][0] + points[i][1] * points[i][1];
pq.add(new int[] {i,sum});
}
int[][] res = new int[k][];
while(k > 0){
res[k-1] = points[pq.poll()[0]];
k--;
}
return res;
}